<template>
  <div id="join" ref="join">
    <el-affix :offset="50" class="affix">
      <el-anchor direction="horizontal" class="anchor" @click="handleClick" :bound="100" :offset="100"
        :container="join">
        <el-anchor-link class="anchor-link" v-for="(item, index) in tabsList" :href="`#label-${index == 3 ? 4 : index}`"
          :key="item.key">
          {{ item.label }}
        </el-anchor-link>
      </el-anchor>
    </el-affix>
    <!-- <van-form @submit="onSubmit">
    <van-cell-group inset> -->
    <div style="margin-bottom: 10px;"></div>
    <div class="wrap" v-for="(el, idx) in titleList" :key="el.label">
      <div class="label islabelflag" :id="`label-${idx}`" v-if="el.label">{{ el.label }}</div>
      <div class="tip tipToopMsg" v-if="el.tip?.length > 0">{{ el.tip }}</div>
      <div v-for="item in el.list" :key="item.label" v-show="item.show" :id="`list-${item.id}`" class="list-item">
        <!-- ${item.label.replace(/\（.*?\）/g, '')} -->
        <div v-if="item.preTip" :class="['pre-tip', item.asTitle ? 'as-title' : '']">
          <div>{{ item.preTip }}</div>
        </div>
        <span
          :class="[getExclude(item) ? '' : 'filed-wrap', 'relative', item.names == 'birthday' || item.names == 'intentionDate' ? 'flexAlignCenter' : '']">
          <div class="filed-top" v-show="item.label">
            <div v-show="!item.isNotVal" :class="[
              'label-title',
              item.asTitle && !item.preTip ? 'as-title' : '',
              item.mainTitle ? 'label' : '',
            ]">
              {{ item.label?.split('（')[0] }}
              <span id="introduce" style="color:#209ee4;" v-if="item.label?.split('（')[1]">({{
                item.label?.split('（')[1]?.replace('）', '')
              }})</span>
              <span v-show="item?.rules ? item?.rules[0]?.required : false">*</span>
              <span v-if="item?.names == 'certificateType'">
                <van-popover v-model:show="showPopover" placement="right" theme="dark">
                  <div style="padding:20px;">
                    <!-- {{ item?.tip }} -->
                    1、中国大陆籍请填写身份证信息，该信息作为身份识别的重要依据。<br />
                    2、每人仅允许填写一次个人证件类型及证件号码。简历提交成功后无法自助修改。
                    如确有修改需求，请将修改原因，新旧证件具体信息等证明材料发送到ftzhaopin@fangtian.me邮箱说明。<br />
                    3、每人仅允许注册和使用一份简历应聘，在个人简历信息注册完成后，
                    使用本人其他类型证件（如护照、港澳永久身份证、台胞证等）注册新简历的行为、
                    或通过修改及编纂身份证号以新增注册简历的行为，将被视为重复注册和使用简历应聘。
                    重复注册简历应聘的行为一经发现将取消当前面试和录用资格。 <br />
                    4、若出现证件信息被占用的情况，请发邮件到ftzhaopin@fangtian.me邮箱说明。
                  </div>
                  <template #reference>
                    <van-icon name="question-o" />
                  </template>
                </van-popover>
              </span>
              <span v-if="item?.names == 'imgae'" style="color:#B3C0C8;">(请上传2M以内的png/jpg)</span>
            </div>
            <span v-show="item.showError && item?.rules[0]?.required" :class="['error-msg']">{{
              `此为必填项`
            }}</span>
          </div>
          <template v-if="item.component === 'divider'">
            <div class="label">{{ item.label }}</div>
            <van-divider :style="{ borderColor: '#409eff' }" />
          </template>
          <template v-if="item.component === 'upload'">
            <div class="upload-container">
              <van-uploader :after-read="afterRead" accept=".png,.jpg,.JPG,.PNG" result-type="file" v-model="item.value"
                :max-size="2048 * 1024" preview-size="100" :max-count="1" @oversize="onOversize">
                <div class="upload-btn upload-pic">
                  <span class="iconfont icon-xiangji"></span>
                  <span>添加照片</span>
                </div>
              </van-uploader>
            </div>
            <van-divider />
          </template>
          <van-field @input="item.value = item.value.replace(regStr, '')" v-if="item.component == 'input'"
            v-model="item.value" :placeholder="`请输入${item.label}`" :rules="item.rules" label-align="top"
            :maxlength="item.maxlength" :type="item.type"
            :formatter="item.label == '电子邮箱' ? EmailFormatter : cardFormatter" />
          <van-field v-if="item.component == 'textarea'" v-model="item.value" class="textarea-container"
            :placeholder="`请输入${item.label}`" :rules="item.rules" rows="2" type="textarea" autosize label-align="top"
            :maxlength="item.maxlength" :formatter="cardFormatter" />
          <template v-if="item.component == 'select'">
            <van-field :rules="item.rules" v-model="item.value" is-link readonly name="picker"
              :placeholder="`请选择${item.label}`" @click="item.showPicker = true" label-align="top" />
            <van-popup v-model:show="item.showPicker" position="bottom">
              <van-picker :columns="item.columns"
                @confirm="({ selectedOptions }) => confirmSelect(item, selectedOptions)"
                @cancel="item.showPicker = false" />
            </van-popup>
          </template>
          <template v-if="item.component == 'datePicker'">
            <van-field label-align="top" v-model="item.value" :rules="item.rules" class="date-picker" is-link readonly
              name="datePicker" placeholder="点击选择时间" @click="item.showPicker = true" />
            <van-popup v-model:show="item.showPicker" position="bottom">
              <van-date-picker @confirm="({ selectedValues }) => confirmDatePicker(item, selectedValues)"
                @cancel="item.showPicker = false" :min-date="item.minDate" :max-date="item.maxDate"
                :columns-type="columnsType" :formatter="formatter" />
            </van-popup>
          </template>
          <template v-if="item.component == 'area'">
            <van-field label-align="top" v-model="item.value" :rules="item.rules" is-link readonly name="area"
              placeholder="地区选择" @click="item.showPicker = true" />
            <van-popup v-model:show="item.showPicker" position="bottom">
              <van-area :area-list="areaList" @confirm="({ selectedOptions }) => areaConfirm(item, selectedOptions)"
                @cancel="item.showPicker = false" />
            </van-popup>
          </template>
          <template v-if="item.component == 'checkbox'">
            <div class="sort-wrap" v-if="item.useElement">
              <div v-for="(el, idx) in getSortList(item)" :key="el">
                <span>{{ idx + 1 }}.</span>{{ el }}
              </div>
            </div>
            <el-checkbox-group v-model="item.value" v-if="item.useElement" :max="item.max" size="small">
              <el-checkbox-button shape="square" :class="[item.value.includes(el.name) ? 'active' : '']"
                v-for="el in item.columns" :key="el.name" :value="el.name">
                {{ el.label }}
              </el-checkbox-button>
            </el-checkbox-group>

            <van-checkbox-group v-else v-model="item.value" :max="item.max" :class="item.divide ? 'divide' : ''">
              <van-checkbox :name="ev.name" shape="square" v-for="ev in item.columns"
                :class="item.divide ? '' : 'checkbox-item'">
                {{ ev.label }}
              </van-checkbox>

            </van-checkbox-group>


          </template>
          <template v-if="item.component == 'assembly'">
            <div class="assembly-box">
              <van-field class="select" :rules="item.rules" v-model="item.value[0]" is-link readonly name="picker"
                :placeholder="`请选择${item.label}`" @click="item.showPicker = true" label-align="top" />
              <van-popup v-model:show="item.showPicker" position="bottom">
                <van-picker :columns="item.columns"
                  @confirm="({ selectedOptions }) => confirmSelect(item, selectedOptions)"
                  @cancel="item.showPicker = false" />
              </van-popup>
              <van-field :formatter="cardFormatter" v-show="item.value[0]" class="input" v-model="item.value[1]"
                :placeholder="`具体分数`" :rules="item.rules" label-align="top" />
            </div>
          </template>

          <template v-if="item.component == 'radio'">
            <van-radio-group v-model="item.value" direction="horizontal" :class="item.divide ? 'divide' : ''">
              <van-radio :name="ev.name" v-for="ev in item.columns">{{ ev.label }}</van-radio>
            </van-radio-group>
            <van-field :formatter="cardFormatter" v-if="item.withInput && item.reflectLabel == item.value"
              v-model="item.inputVal" label-align="top" type="textarea" placeholder="请填写其他渠道" class='textArea' />

          </template>
          <template v-if="item.component == 'dateRange'">
            <div class="date-ranger">
              <van-field v-model="item.value[0]" readonly label-align="top" name="datePicker" placeholder="点击选择时间"
                @click="item.showPicker = true" right-icon="calendar-o" />
              <van-popup v-model:show="item.showPicker" position="bottom">
                <van-date-picker :min-date="new Date(1980, 1, 1)" :max-date="new Date(maxDate)"
                  :columns-type="item.names != 'educationalStartTime' ? columnsType : columnsTypeYM"
                  :formatter="formatter" @confirm="({ selectedValues }) => {
                    confirmDateRange(selectedValues, item, 0);
                  }
                    " @cancel="item.showPicker = false" />
              </van-popup>
              <span>—</span>
              <van-field v-model="item.value[1]" readonly label-align="top" name="datePicker" placeholder="点击选择时间"
                @click="item.showPicker1 = true" right-icon="calendar-o" />
              <van-popup v-model:show="item.showPicker1" position="bottom">
                <van-date-picker :min-date="new Date(1980, 1, 1)" :max-date="new Date(maxDate)"
                  :columns-type="item.names != 'educationalStartTime' ? columnsType : columnsTypeYM"
                  :formatter="formatter" @confirm="({ selectedValues }) => {
                    confirmDateRange(selectedValues, item, 1);
                  }
                    " @cancel="item.showPicker1 = false" />
              </van-popup>
            </div>
          </template>
          <template v-if="item.component == 'remote'">
            <el-select v-model="item.value" filterable remote reserve-keyword :remote-method="(val: string) => {
              getShcool(val, item);
            }
              " :loading="item.loading" style="width: 100%" placeholder="请输入学校名称">
              <el-option v-for="ev in item.columns" :key="ev.value" :label="ev.label" :value="ev.value" />
              <template #loading>
                <svg class="circular" viewBox="0 0 50 50">
                  <circle class="path" cx="25" cy="25" r="20" fill="none" />
                </svg>
              </template>
            </el-select>
          </template>
          <template v-if="item.component === 'del'">
            <div class="can-del" @click="delModule(el, item)">
              <van-icon name="delete-o" />
              删除
            </div>
          </template>
          <template v-if="item.component == 'add'">
            <div class="add-btn" @click="addList(item)">
              <span class="iconfont icon-tianjia"></span>
              <span>{{ item.label }}</span>
            </div>
          </template>
          <template v-if="item.component === 'uploadarea'">
            <div class="upload-container">
              <div class="upload-wrap">
                <van-uploader accept=".doc,.docx,.pdf" :max-size="2048 * 1024" @oversize="onOversize"
                  v-model="item.value" :max-count="1" reupload>
                  <template #preview-cover="{ file }">
                    <div class="upload-size">{{ getSize(file.size) }}</div>
                  </template>
                  <template #preview-delete>
                    <van-icon name="cross" class="upload-cross" />
                  </template>
                  <template #default>
                    <div class="upload-btn">
                      <span class="iconfont icon-shangchuan"></span>
                      <span>上传文件</span>
                    </div>
                  </template>
                </van-uploader>
                <div class="upload-tip" v-for="(el, idx) in item.tips" :key="idx">
                  <span> {{ idx + 1 }}.{{ el }}</span>
                </div>
              </div>
            </div>
          </template>
        </span>
        <div class="tip" v-if="item.tip?.length > 0">
          {{ item.tip }}
        </div>
        <!-- 不填写默认显示 -->
        <van-divider v-if="!item.Vandivide" />
      </div>

    </div>

    <div class="accept">
      <van-checkbox v-model="accept" class="chekbox" shape="square"> </van-checkbox>
      <div class="right">
        我承诺以上提供的内容完全属实，如本声明及其他部分系伪造或不正确，本人同意并接受方田可随时终止同我签订的协议或合同。
        <!--<span class="_primary" @click="toPravite">《隐私政策》</span> -->
      </div>
      <van-divider :style="{ borderColor: '#409eff' }" />
    </div>
    <div style="height: 10px;"></div>
    <!-- </van-cell-group> -->
    <div class="bottm_content">
      <div class="submit-btn" @click="onSubmit">提交简历</div>
    </div>

    <!-- </van-form> -->
  </div>

  <van-back-top target="#join" right="8vw" bottom="16vh" class="custom">

    <img src="../../assets/img/toTop.png" style="width:50px" class="back-to-top-img" alt="" srcset="" />

  </van-back-top>

  <ImageCropper v-if="cropperVisible" :imgUrl="imgUrl" @close="cropperVisible = false" @success="cropperSuccess" />
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { areaList } from '@vant/area-data';
import { showConfirmDialog, showToast } from 'vant';
import { titleList, addList, doReduce, getShcool } from './data';
import { useScroll } from '@vueuse/core';
import type { ListItem, TitleListItem } from './data';
import ImageCropper from '../../components/ImageCropper.vue'
import apis from '../../api/index';
const { saveUserResumes, uploadUserImage, uploadAttachment } = apis;
import { localUserinfo } from '../../assets/js/common';
const showPopover = ref(false);
const userInfo = localUserinfo();

const cropperVisible = ref(false)
const imgUrl = ref()
const regStr = /[\u{1F600}-\u{1F64F}]/gu;
const router = useRouter();
const active = ref<number>(0);
const join = ref<HTMLElement | null>(null);
const { y } = useScroll(join, { behavior: 'smooth', throttle: 200 });
//让时间选择获取到最新的日期
const selfData = ref(['2021', '01', '01']);
const selfYearMouth = ref(['2021', '01']);
// 获取当前日期
const currentDate = new Date();

// 计算四年后的时间戳
const fourYearsLater = new Date(currentDate.getFullYear() + 4, currentDate.getMonth(), currentDate.getDate());

// 设置最大日期
const maxDate = fourYearsLater.toISOString().split('T')[0]; // 转换为 YYYY-MM-DD 格式

const cardFormatter = (value) => {
  // 这里仅用于格式化显示，不控制输入  
  return value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi, ''); //  
};
const EmailFormatter = (value) => {
  return value.replace(/[\u4e00-\u9fa5]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi, '')
}
// 打开裁剪
function afterRead(file: any) {
  //图片加载完成 进行裁剪
  file = file.file
  const fileReader = new FileReader()
  fileReader.readAsDataURL(file)
  fileReader.onload = () => {
    imgUrl.value = fileReader.result
    cropperVisible.value = true
  };
}
// 裁剪成功
function cropperSuccess(data: any) {
  titleList.value.forEach(v => {
    if (v.label == '基础信息') {
      v.list.forEach(v2 => {
        if (v2.component == 'upload') {
          v2.value = data
        }
      })
    }
  })
}

onMounted(() => {
  const clickStatus = JSON.parse(localStorage.getItem('clickStatus'));
  if (clickStatus.resumesStatus == 1) {
    router.push("/");
  }
  let parts = clickStatus.currentDay.split(" ")[0].split("-");
  selfData.value = parts;
  selfYearMouth.value = [parts[0], parts[1]];

  // 刚进页面初始化
  titleList.value.forEach((el) => {
    el.list.forEach((v) => {
      v.showError = false;
    });
  });
});

const tabsList = ref([
  { label: '基础信息', key: '1' },
  { label: '求职意向', key: '2' },
  { label: '个人经历', key: '3' },
  { label: '其他信息', key: '4' },
]);

// let ticking = false;
// watch(y, () => {
//   if (!ticking) {
//     window.requestAnimationFrame(() => {
//       let list = [0, 1, 2, 4];
//       let offsetList: number[] = [];
//       list.forEach((el) => {
//         let element = document.getElementById(`label-${el}`) as HTMLElement;
//         if (element) {
//           offsetList.push(element.offsetTop);
//         }
//       });
//       let newActive = active.value;
//       for (let i = 0; i < offsetList.length; i++) {
//         if (y.value <= offsetList[i]) {
//           newActive = i;
//           break;
//         }
//       }
//       if (active.value !== newActive) {
//         active.value = newActive;
//       }
//       ticking = false;
//     });
//     ticking = true;
//   }
// });

watch(
  titleList,
  (val) => {
    val.forEach((el) => {
      el.list.forEach((item) => {
        if (item.component == 'dateRange') {

          if (item.value[0] != '' && item.value[1] != '') {
            item.showError = false;
          }
        } else if (item.component == 'assembly') {
          if ((item.value[0] && item.value[1]) || !item.value[0]) {
            item.showError = false;
          }
        } else if (Array.isArray(item.value)) {

          if (item.value.length !== 0) {
            item.showError = false;
          }
        } else if (item.component == 'radio' && item.withInput) {
          if (item.inputVal && item.reflectLabel == item.value) {
            item.showError = false;
          } else if (item.value !== '' && item.reflectLabel !== item.value) {
            item.showError = false;
          }
        } else if (item.value.trim() !== '') {
          item.showError = false;
        }
      });
    });
  },
  { deep: true }
);

const smoothScroll = (className: string, append: string | number | undefined) => {
  let anchor = document.getElementById(`${className}-${append}`) as HTMLElement;
  anchor.scrollIntoView({
    behavior: 'smooth',
    block: 'start',
  });
  y.value = anchor.offsetTop - 120;
};

const confirmSelect = (item: ListItem, selectedOptions: any) => {

  if (item.component == 'assembly') {
    item.value[0] = selectedOptions[0]?.text;
  } else {
    item.value = selectedOptions[0]?.text;
  }
  item.showPicker = false;
};
const confirmDatePicker = (item: ListItem, selectedValues: any) => {

  item.value = selectedValues.join('-');

  item.showPicker = false;
};

const areaConfirm = (item: ListItem, selectedOptions: any) => {
  item.showPicker = false;
  item.value = selectedOptions.map((el: any) => el.text).join('/');
};
const delModule = (el: TitleListItem, item: ListItem) => {
  doReduce(item);
};

const accept = ref<boolean>(false);
const columnsType = ref<any[]>(['year', 'month', 'day']);
const columnsTypeYM = ref<any[]>(['year', 'month']);
const formatter = (type: string, option: any) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  if (type === 'day') {
    option.text += '日';
  }
  return option;
};
const getSize = (size: number): string => {
  let kb = size / 1024;
  if (kb > 1024) {
    return Math.ceil(kb / 1024) + 'MB';
  } else {
    return Math.ceil(kb) + 'KB';
  }
};

const toPravite = () => {
  router.push('./privacy')
};
const validate = (item: ListItem): void => {
  if (Array.isArray(item.value)) {
    if (item.value.length === 0) {
      if (item.component === "upload" || item.component === "uploadarea") {
        item.showError = false;
      } else {
        item.showError = true;
      }
    }
    if (item.component === 'assembly') {
      if (item.value[0] && item.value[1] === '') {
        item.showError = true;
      }
    }
    if (item.component == 'dateRange') {
      if (item.value[0] === '' || item.value[1] === '') {
        item.showError = true;
      }
    }
  } else if (item.component === 'radio') {

    if (item.value == item.reflectLabel && item.inputVal == '' && item.withInput === true) {
      item.showError = true;
    }
    if (item.value.trim() == '') {
      item.showError = true;
    }
  } else if (item.value.trim() === '') {
    item.showError = true;
  }
};


const onSubmit = async () => {

  let map: { [key: string]: string } = {};

  const finalList: ListItem[] = [];
  const list = titleList.value;
  for (let i = 0; i < list.length; i++) {
    let el = list[i].list;
    for (let j = 0; j < el.length; j++) {
      let item = el[j];
      if (item.isNotVal || item.show == false) {
        continue;
      }
      validate(item);
      if (!item.isNotVal && item.show == true) {
        finalList.push(item);
      }
    }
  }
  const isPass = finalList.every((el) => !el.showError);
  if (!isPass) {
    const failedItem = finalList.find((el) => !!el.showError);
    const res = await showConfirmDialog({
      title: '提示',
      message: '存在必填信息未填写，请填写完毕后重新提交简历',
    });
    if (!res) return;
    smoothScroll('list', failedItem?.id);
    return;
  }
  if (!accept.value) {
    showToast('请勾选承诺');
    return;
  }
  finalList.forEach((el: ListItem) => {
    map[el.names] = el.value;
  });
  //return false;
  //判定图片存在再取 和文件一样
  const formdata = new FormData();
  if (titleList.value[0].list[0].value.length > 0) {

    formdata.append('file', titleList.value[0].list[0].value[0].file);
    formdata.append('userId', userInfo.userId);

  }
  //上传图片
  //const formdata = new FormData();
  //formdata.append('file', titleList.value[0].list[0].value[0].file);
  //formdata.append('userId', userInfo.userId);
  //let loadimg = await uploadUserImage(formdata);
  //上传附件
  const formdatafile = new FormData();

  if (titleList.value[10].list[0].value.length > 0) {
    formdatafile.append('file', titleList.value[10].list[0].value[0].file);
    formdatafile.append('userId', userInfo.userId);
  }
  //获取杯赛参数
  const competitionnewData = titleList.value[4].list.filter(item => item.names !== "dels");
  const transformedData: any[] = [];
  let currentCompetition: { competitionLevel: any; competitionType?: any; } | null = null;
  competitionnewData.forEach(item => {
    if (item.names === "competitionType") {
      // 创建一个新的竞赛对象
      currentCompetition = {
        competitionType: item.value,
        competitionLevel: ""
      };
    } else if (item.names === "competitionLevel") {
      // 更新竞赛对象中的等级/奖项
      currentCompetition.competitionLevel = item.value;
      // 将竞赛对象添加到转换后的数组中
      transformedData.push(currentCompetition);
    }
  });

  //获取家庭成员参数  1.0版本放弃收集家庭
  // const familynewData = titleList.value[6].list.filter(item => item.names !== "dels");

  // const familytransformedData: any[] = [];
  // let familycurrentCompetition: any = null;
  // familynewData.forEach(item => {
  //   if (item.names === "relation") {
  //     // 创建一个新的竞赛对象
  //     familycurrentCompetition = {
  //       relation: item.value,
  //       name: "",
  //       age: '',
  //       phone: "",
  //       workPlace: "",
  //       occupation: ''
  //     };
  //   } else if (item.names === "name") {
  //     // 更新
  //     familycurrentCompetition.name = item.value;
  //   } else if (item.names === "age") {
  //     familycurrentCompetition.age = item.value;
  //   } else if (item.names == 'phone') {
  //     familycurrentCompetition.phone = item.value;
  //   } else if (item.names == 'workPlace') {
  //     familycurrentCompetition.workPlace = item.value;
  //   } else if (item.names == 'occupation') {
  //     familycurrentCompetition.occupation = item.value;
  //     // 将竞赛对象添加到转换后的数组中
  //     familytransformedData.push(familycurrentCompetition);
  //   }
  // });

  //获取工作经历
  const workExperiencenewData = titleList.value[3].list.filter(item => item.names !== "dels");
  const workExperiencetransformedData: any[] = [];
  let workExperiencecurrentCompetition: any = null;
  workExperiencenewData.forEach(item => {
    if (item.names === "workPlace") {
      // 创建一个新的竞赛对象
      workExperiencecurrentCompetition = {
        workPlace: item.value,
        workPost: "",
        workStartDate: '',
        workEndDate: "",
        workDetail: "",
      };
    } else if (item.names == 'workPost') {
      workExperiencecurrentCompetition.workPost = item.value;
    } else if (item.names == 'workStartDate') {
      //这个地方时时间，要把它转为两个开始和结束时间放进去
      workExperiencecurrentCompetition.workStartDate = item.value[0];
      workExperiencecurrentCompetition.workEndDate = item.value[1];
    } else if (item.names == 'workDetail') {
      workExperiencecurrentCompetition.workDetail = item.value;
      // 将竞赛对象添加到转换后的数组中
      workExperiencetransformedData.push(workExperiencecurrentCompetition);
    }
  });

  //获取教育培训时间
  const educationnewData = titleList.value[2].list.filter(item => item.names !== "dels");
  const educationtransformedData: any[] = [];
  let educationcurrentCompetition: any = null;
  const newHight = educationnewData.slice(0, 2);
  newHight.forEach(item => {
    if (item.names === "schoolName") {
      // 创建一个新的对象
      educationcurrentCompetition = {
        schoolName: item.value,
        qualificationType: item.preTip.slice(item.preTip.indexOf("-") + 1),
      };
    } else if (item.names === "educationalStartTime") {
      educationcurrentCompetition.educationalStartTime = item.value[0];
      educationcurrentCompetition.educationalEndTime = item.value[1];
      educationtransformedData.push(educationcurrentCompetition);
    }
  });

  educationnewData.slice(2).forEach(item => {
    if (item.names === "schoolName") {
      // 创建一个新的竞赛对象
      educationcurrentCompetition = {
        schoolName: item.value,
        educationalStartTime: "",
        schoolDepartment: "",
        specialty: "",
        qualificationType: item.preTip.slice(item.preTip.indexOf("-") + 1),
      };
    } else if (item.names === "educationalStartTime") {
      // 更新竞赛对象中的等级/奖项
      educationcurrentCompetition.educationalStartTime = item.value[0];
      educationcurrentCompetition.educationalEndTime = item.value[1];
      // 将竞赛对象添加到转换后的数组中
    } else if (item.names === "schoolDepartment") {
      educationcurrentCompetition.schoolDepartment = item.value;
    } else if (item.names === "specialty") {
      educationcurrentCompetition.specialty = item.value;
      educationtransformedData.push(educationcurrentCompetition);
    }
  });


  const competitionRequestList = titleList.value[4].list;
  const familyMemberList = titleList.value[6].list;
  const workExperienceList = titleList.value[3].list;
  const EducationalList = titleList.value[2].list;
  const lognData = {
    "userId": userInfo.userId ?? "",//ok
    "userName": map.userName,
    "sex": map.sex ?? "",//ok
    //"certificateType": map.certificateType ?? "",//ok
    //"certificateNumber": map.certificateNumber ?? "",//ok
    "email": map.email ?? "",//ok
    "birthday": map.birthday ?? "",//ok
    "birthplace": map.birthplace ?? "",//ok
    "intentionDate": map.intentionDate,
    "intentionPostList": Object.values(map.intentionPostList) ?? "",//ok
    "intentionGrade": Object.values(map.intentionGrade) ?? "",//ok
    "intentionPlace": Object.values(map.intentionPlace) ?? "",//ok
    "intentionSubject": Object.values(map.intentionSubject) ?? "",//ok  这里时新添加的选择学科
    "competitionRequestList": transformedData,
    "foreignLanguagesGrade": map.foreignLanguagesGrade?.[0] ?? "",//ok
    "foreignLanguagesScore": map.foreignLanguagesGrade?.[1] ?? '',//ok
    //"familyMemberList": "",//1.0版本不需要先传空 familytransformedData
    "workExperienceList": workExperiencetransformedData,
    "educationalList": educationtransformedData,
    "isRecommends": map.isRecommends ?? "",//ok
    "recommendsName": map.recommendsName ?? "",//ok
    "recommendsPhone": map.recommendsPhone ?? "",//ok
    //"accessoryUrl": map.accessoryUrl,//文件单独上传
    // "crmUserId": map.crmUserId,//后台参数
    //"region": map.region,//后台参数
    "standards": Object.values(map.standards).join("-") ?? "",//ok
    "source": list[7].list[0].value == '其他' ? list[7].list[0].inputVal : map.source,//ok 这里要判定是选的其他渠道 还是 非填写
  }
  //return false;
  if (titleList.value[0].list[0].value.length > 0 && titleList.value[10].list[0].value.length > 0) {
    //图片和简历文档都有
    let loadimg = await uploadUserImage(formdata);
    //一层一层调用
    if (loadimg.code == '10000') {
      let loadimgfile = await uploadAttachment(formdatafile);
      if (loadimgfile.code == "10000") {
        let saveData = await saveUserResumes({
          ...lognData,
          imgae: loadimg.data,
          accessoryUrl: loadimgfile.data,
        });

        if (saveData.code == "10000") {
          showToast(saveData.msg)
          router.push({
            path: '/delivered',
            query: {
              identifier: 'delivered',
            },
          });
        }
      }
    }
  } else if (titleList.value[0].list[0].value.length == 0 && titleList.value[10].list[0].value.length == 0) {
    //简历文档和图片都没有

    let saveData = await saveUserResumes(lognData);
    if (saveData.code == "10000") {
      showToast(saveData.msg)
      router.push({
        path: '/delivered',
        query: {
          identifier: 'delivered',
        },
      });
    }
  } else if (titleList.value[0].list[0].value.length > 0 && titleList.value[10].list[0].value.length == 0) {
    //图片，有简历文档没有
    let loadimg = await uploadUserImage(formdata);
    //一层一层调用
    if (loadimg.code == '10000') {
      let saveData = await saveUserResumes({
        ...lognData,
        imgae: loadimg.data,
      });
      if (saveData.code == "10000") {
        showToast(saveData.msg)
        router.push({
          path: '/delivered',
          query: {
            identifier: 'delivered',
          },
        });
      }
    }
  } else if (titleList.value[0].list[0].value.length == 0 && titleList.value[10].list[0].value.length > 0) {
    let loadimgfile = await uploadAttachment(formdatafile);
    if (loadimgfile.code == "10000") {
      let saveData = await saveUserResumes({
        ...lognData,
        accessoryUrl: loadimgfile.data,
      });
      if (saveData.code == "10000") {
        showToast(saveData.msg)
        router.push({
          path: '/delivered',
          query: {
            identifier: 'delivered',
          },
        });
      }
    }
  }
};
const onClickTab = (val: any) => {
  if (val.name == 3) {
    val.name = 4;
  }
  smoothScroll('label', val.name);
};

const getSortList = (item: ListItem): string[] => {
  let list: string[] = [];
  item.value.forEach((el: string[]) => {
    item.columns.forEach((v: any) => {
      if (el === v.name) {
        list.push(v.label);
      }
    });
  });
  return list;
};

const onOversize = () => {
  showToast('文件大小不能超过 2M');
};
const getExclude = (item: ListItem): boolean => {
  let list = [
    'textarea',
    'add',
    'upload',
    'assembly',
    'checkbox',
    'uploadarea',
    'dateRange',
    'datePicker',
  ];
  return !!(list.find((el) => el === item.component) || item.asTitle || item.withInput);
};
function isEarlierDate(dateStr1, dateStr2) {
  if (dateStr2 === "") {
    // 如果 dateStr2 为空字符串，则认为第一个日期总是早于它
    return true;
  }
  const date1 = new Date(dateStr1);
  const date2 = new Date(dateStr2);
  return date1 < date2;
}
const confirmDateRange = (selectedValues: any, item: ListItem, idx: number) => {
  if (idx == 1) {
    if (isEarlierDate(item.value[0], selectedValues.join('-'))) {
      item.value[idx] = selectedValues.join('-');
    } else {
      if (item.value[0] == '') {
        showToast('请先选择起始时间');
      } else {
        showToast('结束时间不能大于开始时间');
      }

    }
  } else {
    item.value[idx] = selectedValues.join('-');
  }
  item.showPicker = false;
  item.showPicker1 = false;
};

const handleClick = (e: MouseEvent) => {
  e.preventDefault();
};
</script>
<style lang="less" scoped>
:deep(.van-checkbox__icon .van-icon) {
  border-radius: 5px;
}

:deep(.el-select__wrapper) {
  border: none;
  box-shadow: none;
}

.textArea {
  background: #F5F7FB;

  :deep(textarea) {
    padding: 0 10px;
  }

  &::after {
    border: none;
  }
}

:deep(.van-tabs) {
  background: #f6f8f9;
}

:deep(.van-field) {
  padding-left: 0;
  padding-right: 0;
}

:deep(.van-checkbox-group .van-checkbox) {
  padding: 10px 0;
  border-bottom: 1px line #B3C0C8;
}

:deep(.van-radio-group .van-radio) {
  padding: 10px 0;
}

:deep(.el-checkbox-group) {
  margin-top: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px 5px;

  .el-checkbox-button__inner {
    border: 1px solid rgba(179, 192, 200, 0.3);
    border-radius: 5px;
    height: 34px;
    line-height: 24px;
  }
}

:deep(.van-popup--bottom) {
  border-radius: 10px 10px 0 0;
}

.custom {
  background: none !important;
}

:deep(.date-ranger .van-cell::after) {
  border: none;
}

:deep(.van-cell) {
  &::after {
    border: none;
  }
}

// :deep(.van-field__body) {
//   textare {
//     background: #f5f7fb;
//   }
// }
#join {
  background: #f5f7fb;
  width: 100vw;
  padding: 0px 10px;
  padding-bottom: 40px;
  box-sizing: border-box;
  height: calc(100vh);
  overflow: auto;
  overflow-x: hidden;
  padding-top: 50px;
}

.wrap {
  box-sizing: border-box;
  background: #fff;
  padding: 12px 12px;
  box-sizing: border-box;
  margin-bottom: 20px;
  border-radius: 10px;

  .label {
    font-size: 17px;
    font-weight: 600;
    // line-height: 25px;
    letter-spacing: 0px;
    color: #212121;
    margin-bottom: 10px;
  }
}

.list-item {
  position: relative;
}

.upload-container {
  // padding: 0 15px;
  margin-top: 15px;
  box-sizing: border-box;
}

.filed-wrap {
  display: flex;
  align-items: center;
}

.filed-top {
  min-width: 120px;
  position: relative;
  display: flex;
  margin-right: 10px;
  justify-content: space-between;

  .label-title {
    span {
      font-size: 16px;
      color: red;
    }
  }

  .error-msg {
    color: red;
    font-size: 12px;
    position: absolute;
    left: 0;
    top: 20px;
  }
}

.tip {
  white-space: pre-line;
  font-size: 16px;
  font-weight: normal;
  line-height: 30px;
  letter-spacing: 0em;
  color: #9f9f9f;
  margin-bottom: 17px;
  margin-top: 10px;
}

.mt-10 {
  margin-top: -13px !important;
}

.mt-20 {
  margin-top: 34px !important;
}

.tipToopMsg {
  padding: 10px;
  background: #F5F7FB;
  color: #8C969D;
  position: relative;

  &:after {
    content: "";
    position: absolute;
    top: -8px;
    /* 根据需要调整位置 */
    left: 30px;
    margin-left: -10px;
    /* 宽度的一半，确保三角形居中 */
    border-left: 5px solid transparent;
    /* 左边框透明 */
    border-right: 5px solid transparent;
    /* 右边框透明 */
    border-bottom: 10px solid #F5F7FB;
    /* 底部边框为黑色，形成向上的三角形 */
    width: 0;
    height: 0;
  }
}


.pre-tip {
  // pont-size: 15px;
  font-weight: 500;
  line-height: 25px;
  letter-spacing: 0px;
  color: #209ee4;
  margin-bottom: 10px;
  position: relative;
  font-size: 16px;
  // display: flex;
}

.flexAlignCenter {
  display: flex;
  align-items: baseline;
}


.date-ranger {
  display: flex;
  align-items: center;
  margin-top: 15px;

  span {
    width: 30%;
    line-height: 0px;
    text-align: center;
  }
}

.checkbox-item {
  margin-top: 14px;
}

.can-del {
  position: absolute;
  right: 0;
  top: 0px;
  z-index: 100;
  color: #ff4242;
}

.assembly-box {
  margin-top: 15px;
  display: flex;
  align-items: flex-end;

  .select {
    width: 50%;
    margin-right: 20px;
  }
}

.divide {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px 0;
  margin-top: 15px;
}

.upload-wrap {
  width: 88vw;
  height: 119px;
  opacity: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 外部/Light Gray/Light Gray 5 */
  box-sizing: border-box;
  /* 外部/Light Gray/Light Gray 3 */
  position: relative;

  :deep(.van-uploader__file) {
    width: 320px;
    border-radius: 5px;
    margin: 0 auto;
    display: flex;
    flex-direction: row;
    padding: 0 16px;
    box-sizing: border-box;
    align-items: center;

    .van-uploader__file-icon {
      font-size: 40px;
      color: #6d9fe5;
      width: 50px;
    }

    .van-uploader__file-name {
      text-align: left;
      font-size: 14px;
      color: #333;
      flex: 1;
      padding-right: 40px;
      margin-top: 0;
      margin-bottom: 20px;
    }
  }

  :deep(.van-uploader__preview-delete) {
    top: 0px;
    right: 100px;
    background: #f56c56;
  }
}

.upload-tip {
  font-size: 14px;
  font-weight: normal;
  line-height: 12px;
  text-align: left;
  letter-spacing: 0em;
  position: absolute;
  /* Text/colorTextPlaceholder */
  color: rgba(0, 0, 0, 0.25);
  z-index: 0;
  left: 0;
  top: 110px;

  &:nth-child(2) {
    top: 85px;
  }
}

.accept {
  padding: 0 24px;
  display: flex;
  box-sizing: border-box;
  margin-bottom: 30px;
  align-items: baseline;

  .chekbox {
    width: 30px;
  }

  .right {
    flex: 1;
    font-size: 16px;
    line-height: 30px;
  }
}

:deep(.el-anchor__link.is-active) {
  color: #209ee4;
}

:deep(.el-anchor__marker) {
  background-color: #209ee4;
}

:deep(.date-picker) {
  &::after {
    border: none;
  }
}

.bottm_content {
  position: fixed;
  bottom: 0;
  /* left: 50%; */
  width: 100%;
  left: 0;
  background: #fff;
  height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;

  .submit-btn {
    width: 90%;
    height: 88rpx;
    border-radius: 6px;
    opacity: 1;
    background: #209ee4;
    text-align: center;
    line-height: 45px;
    color: #fff;
  }
}


.theme-color {
  color: #209ee4 !important;
}

.as-title {
  font-size: 16px;
  color: #209ee4;
  margin-bottom: 10px;
  font-weight: 500;
  line-height: 25px;
  letter-spacing: 0px;
}

.textarea-container {
  margin-top: 15px;
  background: #f5f7fb;
  border-radius: 5px;
  box-sizing: border-box;
  margin-bottom: 15px;

  :deep(.van-field__control) {
    padding: 0 10px;
  }
}

.add-btn {
  width: 100%;
  border-radius: 5px;
  background: #f5f7fb;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px;
  box-sizing: border-box;
  font-size: 16px;
  color: #209ee4;
  font-weight: 500;
  margin-top: 10px;

  span {
    &:nth-child(1) {
      font-size: 24px;
      margin-right: 5px;
    }
  }
}

.upload-btn {
  width: 88vw;
  height: 70px;
  background: rgba(32, 158, 228, 0.1);
  border-radius: 10px 10px 10px 10px;
  border: 1px dashed rgba(32, 158, 228, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #209ee4;

  span {
    font-size: 14px;

    &:nth-child(1) {
      font-size: 14px !important;
      margin-right: 5px;
    }
  }
}

.upload-pic {
  width: 90px;
  height: 90px;
  flex-direction: column;
}

.sticky {
  width: 100vw;
  left: -10px;
  position: relative;
  z-index: 999;
  margin-bottom: 10px;
}

.upload-cross {
  position: absolute;
  font-size: 20px;
  right: -80px;
  top: 32px;
}

.upload-size {
  position: absolute;
  font-size: 14px;
  top: 45px;
  left: 70px;
  color: #b3c0c8;
}

.date-picker {
  //margin-top: 15px;
}

.sort-wrap {
  display: flex;
  color: #8893a9;

  div {
    padding: 6px;
    box-sizing: border-box;
    font-size: 14px;
    margin-right: 4px;
    background: #f5f7fb;
    border-radius: 5px;
    display: flex;
    align-items: center;

    span {
      display: block;
      margin-left: 3px;
      width: 16px;
      height: 16px;
      // border-radius: 50%;
      line-height: 16px;
      text-align: center;
      // background: #fff;

      // background: #d3dce6;
    }
  }
}

:deep(.van-divider) {
  margin: 6px 0;
  margin-bottom: 15px;
}

#introduce {
  font-size: 14px;
  color: #000;
  font-weight: 400;
  margin-left: 5px;
}

.active {
  :deep(.el-checkbox-button__inner) {
    background: rgba(32, 158, 228, 0.1);
    border: none; //1px solid rgba(32, 158, 228, 0.1);
    color: #209ee4;
  }
}

.affix {
  z-index: 999;
  position: relative;

  .anchor {
    width: calc(100vw);
    margin-left: -10px;
    padding: 0 20px;
    box-sizing: border-box;
    display: flex;

    .anchor-link {
      flex: 1;

      :deep(a) {
        font-size: 16px !important;
      }

    }

    :deep(.el-anchor__list) {
      width: 100%;
      text-align: center;
    }
  }
}
</style>
